package com.dg11185.nearshop.activity.user;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.net.request.ResetPwdRequest;
import com.dg11185.nearshop.net.request.SendSmsResetCodeRequest;
import com.dg11185.nearshop.net.response.ResetPwdResponse;
import com.dg11185.nearshop.net.response.SendSmsCodeResponse;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.ViewUtils;

/**
 * 
 * @author wanliang527
 * @date 2014-5-16
 * 
 */
public class ResetPassWdActivity extends SubPageActivity {

    private final static int SEND_CODE_RET = 1;
    private final static int RESET_PASS_WD_RET = 2;

    private EditText phone, code, passwd1, passwd2;
    private Button sendCode, submit;

    private boolean isSendCode = false;

    private String num = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_passwd);
        setSubPageTitle("重置密码");
        initView();
    }

    private void initView() {
        findViewsId();
        sendCode.setOnClickListener(clickListener);
        submit.setOnClickListener(clickListener);
    }

    private void findViewsId() {
        phone = (EditText) findViewById(R.id.edit_phone);
        sendCode = (Button) findViewById(R.id.btn_send_code);
        code = (EditText) findViewById(R.id.edit_code);
        passwd1 = (EditText) findViewById(R.id.edit_passwd1);
        passwd2 = (EditText) findViewById(R.id.edit_passwd2);
        submit = (Button) findViewById(R.id.btn_submit);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SEND_CODE_RET:
                    SendSmsCodeResponse res1 = (SendSmsCodeResponse) msg.obj;
                    onSendCodeRet(res1);
                    break;

                case RESET_PASS_WD_RET:
                    ResetPwdResponse res2 = (ResetPwdResponse) msg.obj;
                    onResetPassWdRet(res2);
                    break;
            }

        }

        /**
         * 处理发送验证码的返回
         * 
         * @param res
         */
        private void onSendCodeRet(SendSmsCodeResponse res) {
            if (res == null)
                return;
            String status = res.status;
            if (status.equals(SendSmsCodeResponse.SUCCESS)) {
                ViewUtils.showToast(mActivity, "发送成功");
                isSendCode = true;
                phone.setFocusable(false);
            } else if (status.equals(SendSmsCodeResponse.REQ_UN_TIMEOUT)) {
                isSendCode = true;
                ViewUtils.showToast(mActivity, "5分钟内不允许重复请求验证码");
            } else if (status.equals(SendSmsCodeResponse.FAILE)) {
                ViewUtils.showToast(mActivity, "短信发送失败，请稍后再试");
            } else if (status.equals(SendSmsCodeResponse.MEM_NOTFOUND)) {
                ViewUtils.showToast(mActivity, "该手机号尚未注册");
            } else {
                LogUtils.logNetError("发送验证码失败---"+status);
                ViewUtils.showToast(mActivity, R.string.network_error);
            }
        }

        private void onResetPassWdRet(ResetPwdResponse res) {
            if (res == null)
                return;
            String status = res.status;
            if (status.equals(ResetPwdResponse.SUCCESS)) {
                showDialog("重置密码成功", "请返回登录！").setPositiveButton("确定",
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Intent data = new Intent();
                                data.putExtra("phoneNum", num);
                                setResult(RESULT_OK, data);
                                mActivity.finish();
                            }
                        }).setCanceledOnTouchOutside(false);
            } else if (status.equals(ResetPwdResponse.ILLEGAL_VC)) {
                ViewUtils.showToast(mActivity, "验证码错误");
            } else if (status.equals(ResetPwdResponse.MEM_NOTFOUND)) {
                ViewUtils.showToast(mActivity, "该手机号尚未注册");
            } else {
                LogUtils.logNetError("重置密码失败---"+status);
                ViewUtils.showToast(mActivity, R.string.network_error);
            }
        }
    };

    private OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_send_code:
                    num = phone.getText().toString();
                    if (isPhoneValid(num)) {
                        sendCode(num);
                    }
                    break;

                case R.id.btn_submit:
                    String c = code.getText().toString().trim();
                    String passWd = passwd1.getText().toString();
                    if (!isSendCode) {
                        ViewUtils.showToast(mActivity, "请先获取验证码");
                        return;
                    }
                    if (isPhoneValid(num) && isCodeValid(c) && isPasswdValid()) {
                        resetPassWd(num, c, passWd);
                    }
                    break;
            }
        }

        /**
         * 发送验证码
         * 
         * @param num
         *            手机号
         */
        private void sendCode(String num) {
            showLoading();
            SendSmsResetCodeRequest req = new SendSmsResetCodeRequest(num);
            req.setActionListener(new ActionListener<SendSmsCodeResponse>() {

                @Override
                public void onSuccess(SendSmsCodeResponse result) {
                    LogUtils.logNetReturn(Constants.sendSmsResetCode, result.responseStr);
                    hideLoading();
                    Message msg = new Message();
                    msg.what = SEND_CODE_RET;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFailure(int resultCode) {
                    hideLoading();
                    LogUtils.logNetError("发送验证码失败---" + resultCode);
                    if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                        ViewUtils.showToast(mActivity,
                                R.string.cant_connect_network);
                    } else {
                        ViewUtils.showToast(mActivity, R.string.network_error);
                    }
                }
            });
            NetClient.httpPost(req);
        }

        private void onUnKnowError(int resultCode) {
            ViewUtils.showToast(mActivity, "未知错误" + resultCode + "，请稍后再试");
        }

        /**
         * 发起重置密码的网络连接
         * 
         * @param num
         *            手机号码
         * @param code
         *            验证码
         * @param newPasswd
         *            新密码
         */
        private void resetPassWd(String num, String code, String newPasswd) {
            showLoading();
            ResetPwdRequest req = new ResetPwdRequest(num, code, newPasswd);
            req.setActionListener(new ActionListener<ResetPwdResponse>() {

                @Override
                public void onSuccess(ResetPwdResponse result) {
                    LogUtils.logNetReturn(Constants.resetPwd, result.responseStr);
                    hideLoading();
                    Message msg = new Message();
                    msg.what = RESET_PASS_WD_RET;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFailure(int resultCode) {
                    hideLoading();
                    LogUtils.logNetError("发送验证码失败---" + resultCode);
                    if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                        ViewUtils.showToast(mActivity,
                                R.string.cant_connect_network);
                    } else {
                        ViewUtils.showToast(mActivity, R.string.network_error);
                    }
                }
            });
            NetClient.httpPost(req);
        }

    };

    /**
     * 判断手机号码是否合法
     * 
     * @param num
     *            手机号码
     * @return
     */
    private boolean isPhoneValid(String num) {
        if (num == null || !(num.trim().length() == 11)) {
            ViewUtils.showToast(this, "请输入11位有效手机号");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 判断密码是否合法
     * 
     * @return
     */
    private boolean isPasswdValid() {
        String pass1 = passwd1.getText().toString().trim();
        String pass2 = passwd2.getText().toString().trim();
        if (pass1 == null || pass2 == null || pass1.length() == 0
                || pass2.length() == 0) {
            ViewUtils.showToast(mActivity, "两次输入的密码不能为空");
            return false;
        } else if (!pass1.equals(pass2)) {
            ViewUtils.showToast(mActivity, "两次输入的密码不一致");
            return false;
        } else if (pass1.length() < 6) {
            ViewUtils.showToast(mActivity, "密码长度少于6位");
            return false;
        }
        return true;
    }

    /**
     * 判断验证码是否合法
     * 
     * @param c
     *            验证码
     * @return
     */
    private boolean isCodeValid(String c) {
        if (c == null || c.length() == 0) {
            return false;
        }
        return true;
    }

}
